package com.qianxun.module.datasource1.common.manager;

import com.qianxun.module.datasource1.common.constant.CaptchaValidObjectEnum;
import lombok.Data;
import lombok.experimental.Accessors;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 验证对象缓存池
 * @author: huwei
 * @date: 2020/3/9 11:10
 * @version: 1.0.0
 */
public class CaptchaValidObjectHolder {
    /**
     * 验证对象缓存池
     */
    private Map<String ,CaptchaObjectStatus> validObjectBuffer = new ConcurrentHashMap<>();

    /**
     * 初始化：添加系统可进行验证码认证的功能模块，避免缓存不可验证数据，导致内存溢出
     */
    {
        //登录模块验证码验证
        CaptchaValidObjectEnum loginValid = CaptchaValidObjectEnum.LOGIN;
        validObjectBuffer.put(loginValid.getCode() ,new CaptchaObjectStatus(loginValid.getName() ,loginValid.getCode() ,true));
    }

    /**
     * 单例
     */
    private CaptchaValidObjectHolder(){}

    public static CaptchaValidObjectHolder getInstance(){
        return Singleton.instance;
    }

    /**
     * 添加验证码验证状态
     * @param validCode 验证对象编码
     */
    public void add(String validCode){
        if(validCode != null && validObjectBuffer.containsKey(validCode)){
            validObjectBuffer.get(validCode).setStatus(true);
        }
    }

    /**
     * 取消验证码验证状态
     * @param validCode 验证对象编码
     */
    public void cancel(String validCode){
        if(validCode != null && validObjectBuffer.containsKey(validCode)){
            validObjectBuffer.get(validCode).setStatus(false);
        }
    }

    /**
     * 判断是否进行验证码验证
     * @param validCode 验证对象编码
     * @return
     */
    public boolean isValid(String validCode){
        return validCode != null &&  validObjectBuffer.containsKey(validCode) && validObjectBuffer.get(validCode).getStatus();
    }

    /**
     * 获取指定验证对象的验证状态
     * @param validCode 验证名称
     * @return
     */
    public CaptchaObjectStatus get(String validCode){
        return validCode == null ? null : validObjectBuffer.get(validCode);
    }

    /**
     * 获取所有的验证码验证对象状态
     * @return
     */
    public List<CaptchaObjectStatus> getAll(){
        List<CaptchaObjectStatus> res = new ArrayList<>(validObjectBuffer.size());
        validObjectBuffer.forEach((k ,v)->{
            res.add(v);
        });
        return res;
    }

    private static class Singleton {
        private static final CaptchaValidObjectHolder instance = new CaptchaValidObjectHolder();
    }

    /**
     * 验证码验证对象状态
     */
    @Data
    @Accessors(chain = true)
    public class CaptchaObjectStatus {
        String name;
        String code;
        Boolean status;

        public CaptchaObjectStatus(String name ,String code, boolean status) {
            this.name = name;
            this.code = code;
            this.status = status;
        }
    }
}
